﻿/* 5. You are given an array of strings. 
 * Write a method that sorts the array by the length of its elements (the number of characters composing them. */

using System;

public class SortingByLengthOfMembers
{
    public static int length;
    public static string[] stringArray;
    public static int[][] lengthOfMembers = new int[2][];
    
    public static void Main()
    {
        DataInput();
        QuickSort(0, length - 1);
        PrintArray();
    }

    public static void DataInput()
    {
        do
        {
            Console.Clear();
            Console.Write("\nLength of string array: ");
            if (int.TryParse(Console.ReadLine(), out length) && (0 < length))
                break;
        } while (true);

        stringArray = new string[length];
        lengthOfMembers[0] = new int[length];
        lengthOfMembers[1] = new int[length];

        for (int i = 0; i < length; i++)
        {
            Console.Write("array[{0}] = ", i);
            stringArray[i] = Console.ReadLine();
            lengthOfMembers[0][i] = i;
            lengthOfMembers[1][i] = stringArray[i].Length;
        }
    }

    public static void QuickSort(int left, int right)
    {
        if (left >= right)
            return;

        int i = left;
        int j = right;
        int k = lengthOfMembers[1][right];

        while (i < j)
        {
            while ((i < j) && (lengthOfMembers[1][i] <= k))
                i++;

            while ((i < j) && (lengthOfMembers[1][j] >= k))
                j--;

            if (i < j)
                SwapLength(i, j);
        }

        SwapLength(i, right);

        QuickSort(left, i - 1);
        QuickSort(i + 1, right);
    }

    public static void SwapLength(int i, int j)
    {
        int temporary = lengthOfMembers[1][i];
        lengthOfMembers[1][i] = lengthOfMembers[1][j];
        lengthOfMembers[1][j] = temporary;

        temporary = lengthOfMembers[0][i];
        lengthOfMembers[0][i] = lengthOfMembers[0][j];
        lengthOfMembers[0][j] = temporary;
    }

    public static void PrintArray()
    {
        Console.WriteLine("\nSorted array:\n{0}", stringArray[lengthOfMembers[0][0]]);
        for (int i = 1; i < length; i++)
            Console.WriteLine("{0}", stringArray[lengthOfMembers[0][i]]);

        Console.WriteLine();
    }
}